package ms.unicorn.dsl.eistar.reasoning.maxbelief;

import java.util.HashMap;
import java.util.Map;

import eistar.Entity;
import eistar.EvolutionBranch;
import eistar.EvolutionRule;

public class MaxBeliefReasoning {
	
	private Map<Entity, MaxBeliefTable> mbTables;
	
	public MaxBeliefReasoning() {
		mbTables = new HashMap<Entity, MaxBeliefTable>();
	}
	
	public MaxBeliefTable evaluateMaxBelief(EvolutionRule rule) {
		MaxBeliefTable result = openMbTable(rule);
		result.clear();
		result.generateFromModel(rule.getOriginal());
		int defaultMb = 100;
		
		MaxBeliefTable btables = null;
		
		for(EvolutionBranch branch: rule.getBranches()) {
			MaxBeliefTable btable = openMbTable(branch);
			btable.clear();
			btable.generateFromModel(branch);
			btable.setMaxBelief(branch.getProbability());
			btable.setResidualRisk(100 - branch.getProbability());
			// debug-begin
			System.out.println(branch.getName());
			btable.printTableContent(System.out);
			System.out.println("--------");
			// debug-end
			defaultMb -= branch.getProbability();
			
			btables = btables != null ? btables.merge(btable) : btable;
		}
		
		result.setMaxBelief(defaultMb);
		result.setResidualRisk(100 - defaultMb);
		
		result.merge(btables);
			
		return result;
	}
	
	public MaxBeliefTable getMbTable(Entity model) {
		return mbTables.get(model);
	}
	
	public void setMbTable(Entity entity, MaxBeliefTable table) {
		mbTables.put(entity, table);
	}
	
	public MaxBeliefTable openMbTable(Entity entity) {
		MaxBeliefTable res = mbTables.get(entity);
		if (res == null)
			mbTables.put(entity, res = new MaxBeliefTable());
		return res;
	}
}
